<template>
	<view class="contain">
		<view class="info_line">
			<text class="title">收件人</text>
			<input type="text" v-model="needEditAddress.name" />
		</view>
		<view class="info_line">
			<text class="title">电话号码</text>
			<input type="number" v-model="needEditAddress.phoneNumber" />
		</view>
		<view class="info_line" @tap="selectAddress">
			<text class="title">所在地区</text>
			<view class="area_detail">
				{{addressWord}}
			</view>
		</view>
		<view class="info_line">
			<text class="title">详细地址</text>
			<input type="text" v-model="needEditAddress.detailAddress" />
		</view>
		<view class="info_line address">
			<text class="title">设置默认地址</text>
			<switch :checked="needEditAddress.defaultStatus == 1" @change="switchDefaultStatus" />
		</view>
		<view class="delete_btn" v-if="isEdit" @tap="deleteAddress">
			删除收货地址
		</view>
		<uni-popup class="popup" ref="addressSelect" type="bottom" :maskClick="false">
			<view class="popup_c">

				<view class="btn_bar">
					<view class="cancel" @tap="cancel">
						取消
					</view>
					<view class="confirm" @tap="confirm">
						确定
					</view>
				</view>
				<picker-view :indicator-style="indicatorStyle" :value="arrValue" class="picker-view" @change='addressChange'>
					<picker-view-column>
						<view class="item" v-for="(item,index) in area" :key="index">{{item.value}}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in area[arrValue[0]].children" :key="index">
							{{item.value}}
						</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in area[arrValue[0]].children[arrValue[1]].children" :key="index">{{item.value}}</view>
					</picker-view-column>
				</picker-view>
			</view>

		</uni-popup>
		<view @tap="sub" class="save_address">
			保存地址
		</view>
	</view>
</template>

<script>
	import request from '../../../api/request.js';
	import area from "../../../static/area/area.js";
	import WxValidate from '../../../utils/WxValidate.js';
	export default {
		data() {
			return {
				addressList: [],
				needEditAddress: {},
				// 每一个地址的序号
				arrValue: [0, 0, 0],
				lastArrValue: [0, 0, 0],
				// 地区js
				area: area.data,
				//  底部弹出窗的显示
				indicatorStyle: `height: 50px;`,
				// 地址的文字
				addressWord: '',
				isEdit: false
			};
		},
		methods: {
			selectAddress() {
				this.lastArrValue = this.arrValue;
				// 弹出时自动记录当前的位置
				// 如果滑动后没有点击确定，则还是需要重置。
				this.$refs.addressSelect.open()
			},
			// 滚动完成执行的事件
			addressChange(e) {
				let val = e.detail.value;
				this.arrValue = val;
			},
			// 初始化数据
			initAddress(address) {
				let provinceNum = this.area.findIndex(item => {
					return item.value === address.province;
				})
				let cityNum = this.area[provinceNum].children.findIndex(item => {
					return item.value == address.city
				})

				let countryNum = this.area[provinceNum].children[cityNum].children.findIndex(item => {
					return item.value == address.region
				})

				this.arrValue = [provinceNum, cityNum, countryNum];
			},
			// 拼接地区地址字符
			joinCountryStr() {
				const province = this.area[this.arrValue[0]];
				const city = province.children[this.arrValue[1]];
				const country = city.children[this.arrValue[2]];
				this.needEditAddress.province = province.value;
				this.needEditAddress.city = city.value;
				this.needEditAddress.region = country.value;
				this.addressWord = `${province.value}-${city.value}-${country.value}`;
			},
			confirm() {
				this.joinCountryStr();
				this.$refs.addressSelect.close()
			},
			cancel() {
				uni.showToast({
					title: '你取消了选择',
					icon: 'title'
				})
				this.arrValue = this.lastArrValue;
				this.$refs.addressSelect.close();
			},
			// 切换默认地址状态
			switchDefaultStatus(e) {
				this.needEditAddress.defaultStatus = e.detail.value ? 1 : 0;
			},
			err(res) {
				if(res.data.success) {
					uni.showToast({
						title:"成功,1s后跳转页面"
					})
					setTimeout(() => {
						uni.navigateBack()
					},1000)
				} else {
					uni.showToast({
						title:res.data.message,
						icon: "none"
					})						
				}
			},
			// 提交
			async sub() {
				const params = this.needEditAddress;
				if (!this.WxValidate.checkForm(params)) {
					//表单元素验证不通过，此处给出相应提示
					let error = this.WxValidate.errorList[0];
					switch (error.param) {
						case "name":
						case "phoneNumber":
						case "province":
							//TODO
							uni.showToast({
								title: error.msg,
								icon: "none"
							})
							break;

					}
					return false;
				}


				
				if (this.isEdit) {
					// 更新
					const res = await request({
						url: '/address/updateAddressInfo',
						method: 'post',
						data: this.needEditAddress
					})
					this.err(res)
				} else {
					// 新增
					const res = await request({
						url: '/address/addAddressInfo',
						method: 'post',
						data: this.needEditAddress
					})
					this.err(res)
				}
			},
			// 删除
			async deleteAddress() {
				const res = await request({
					url: `/address/delAddressInfo/${this.needEditAddress.id}`,
					method: "delete"
				})
				if (res.data.success === true) {
					uni.showToast({
						title: '删除成功,即将返回'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			},
			// 实例化表单验证
			initValidate() {
				let rules = {
					name: {
						required: true,
						maxlength: 10
					},
					phoneNumber: {
						tel: true,
						required: true
					},
					province: {
						required: true
					}
				}

				let message = {
					name: {
						required: '请输入姓名',
						maxlength: '名字不能超过10个字'
					},
					phoneNumber: {
						tel: "请输入正确的手机号码",
						required: "为输入电话号码"
					},
					province: {
						required: "未选择地址",
					}
				}
				//实例化当前的验证规则和提示消息
				this.WxValidate = new WxValidate(rules, message);
			}

		},
		async onLoad(option) {
			// 实例化验证对象
			this.initValidate();
			// 初始化地址的对象。
			let defaultAddress = {
				"city": "",
				"cityCode": "",
				"createTime": "",
				"defaultStatus": 0,
				"detailAddress": "",
				"id": "",
				"memberId": "",
				"modifyTime": "",
				"name": "",
				"phoneNumber": "",
				"postCode": "",
				"province": "",
				"region": "",
				"tag": ""
			}
			// 根据id判断点击页面的状态,是更改还是新增
			if (option.id) {
				this.isEdit = true
			}
			const res = await request({
				url: "/address/findAllAddress"
			})

			this.addressList = res.data.data.items || [];
			// 地址初始化
			this.needEditAddress = Object.assign(defaultAddress, this.addressList.filter(item => {
				return item.id == option.id
			})[0]);
			// 初始化arrValue
			// 判断一下没有地址的状态
			if (this.needEditAddress.province && this.needEditAddress.city && this.needEditAddress.region) {
				this.initAddress(this.needEditAddress);
				this.joinCountryStr();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.contain {
		width: 95%;
		margin: auto;

		.info_line {
			display: flex;
			align-items: center;
			width: 100%;
			height: 130rpx;
			padding: 30rpx 0;
			border-bottom: 3rpx solid #999999;

			&.address {
				justify-content: space-between;
			}

			.title {
				width: 220rpx;
				color: #999;
			}
		}

		.delete_btn {
			width: 100%;
			height: 100rpx;
			margin-top: 40rpx;
			line-height: 100rpx;
			font-size: $uni-font-size-lg;
			text-align: center;
			left: 100rpx;
			color: #fff;
			background-color: #f00;
		}

		.save_address {
			height: 80rpx;
			width: 500rpx;
			margin: auto;
			margin-top: 300rpx;
			border-radius: 40rpx;
			line-height: 80rpx;
			font-size: $uni-font-size-base;
			text-align: center;
			color: #fff;
			background-color: $themeColor;
		}

		.popup {
			.popup_c {

				height: 600rpx;
				background-color: #fff;

				.btn_bar {
					display: flex;
					justify-content: space-between;
					width: 100%;
					height: 100rpx;
					border-bottom: 3rpx solid #E5E5E5;

					view {
						height: 100rpx;
						text-align: center;
						padding: 20rpx;
					}

					.cancel {
						color: #1aad19;
					}

					.confirm {
						color: rgb(0, 122, 255);
					}
				}

				.picker-view {
					height: 500rpx;
				}
			}
		}

		picker-view {
			width: 100%;
			height: 100rpx;
			text-align: center;
		}
	}
</style>
